import React, { Component } from 'react'
import axios from 'axios'
import {Product} from '../../../types/products'
import {connect} from 'react-redux'
import ProductItem from '../../../components/product'

interface IProps{
    initList:(list:Product[]) => void,
    list:Product[]
}

interface IState{
    list:Product[]
}

class Home extends Component<IProps,IState> {
    componentDidMount(){
        axios.get('/api/list').then(res => {
            this.props.initList(res.data)
        })
    }
    render() {
        let {list} = this.props;
        return (
            <div>
                {list.length && list.map((item:Product) => <ProductItem key={item.id} item={item}></ProductItem>)}
            </div>
        )
    }
}

let stateMapToProps = (state:any) => {
    return {
        list:state.list.list
    }
}
let dispatchMapToProps = (dispatch:any) => {
    return {
        initList(list:Product[]){
            dispatch({type:'INIT_LIST',list})
        }
    }
}
export default connect(stateMapToProps,dispatchMapToProps)(Home)
